import axios from "axios";
import router from "@/router";
import { ElMessage } from "element-plus";

// const store = useStore()

const http = axios.create({
    baseURL: 'http://localhost/api',
    timeout: 3000
});

//请求拦截器
http.interceptors.request.use(
    (config)=>{
        const token  = localStorage.getItem('token')

        if(token!='' || token!=null){
          //如果token不为空，就携带token   
          config.headers['token'] = token
        }
       
        return config
    },
    (error)=>{
        //请求错误做什么
       // return Promise.reject(error)
      // alert("请求异常！")
       ElMessage({message:'请求接口异常',type:'error'})
       return;
    }
)

//响应拦截器
http.interceptors.response.use(
    (res) =>{
    //    //对响应处理
    
   
       const code = res.data.data.code
    
       if(code == 5002 || code ==5003 || code==5004 || code==4001){
          console.log("token错误。。");
          alert(res.data.data.data)
          //跳转到登录页面
          router.push('/login')
       }
        
       return res;
    },
    (error)=>{
       // return Promise.reject(error)
       //alert("响应异常！")
       ElMessage({message:'后端接口异常',type:'error'})
       return;
    }
)

export default http;